// 一次遍历 时间复杂度 O(n) 空间复杂度 O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* preHead = new ListNode(0, head);
        ListNode *pre = preHead, *left = nullptr, *right = nullptr;
        while (head != nullptr) {
            if (left == nullptr) {
                left = head;
                head = head->next;
                continue;
            }
            if (left->val == head->val) {
                right = head;
            }
            else {
                if (right != nullptr) {
                    pre->next = head;
                    left = head;
                    right = nullptr;
                }
                else {
                    pre = left;
                    left = head;
                }
            }
            head = head->next;
        }
        if (right != nullptr) pre->next = nullptr;
        return preHead->next;
    }
};

// 一次遍历 时间复杂度 O(n) 空间复杂度 O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return head;
        ListNode* preHead = new ListNode(0, head);
        head = preHead;
        while (head->next && head->next->next) {
            if (head->next->val == head->next->next->val) {
                int x = head->next->val;
                while (head->next && head->next->val == x) {
                    head->next = head->next->next;
                }
            }
            else {
                head = head->next;
            }
        }
        return preHead->next;
    }
};